import flash.events.Event;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.ListEventReason;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ArrayUtil;
			
/**
 *  This will hold the API player instance once it is initialized.
 **/
private var player:Object;
private var loader:Loader = new Loader();
			
private function initPlayer() { 
	loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
	loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
}
			
private function onLoaderInit(event:Event):void {
	middlePanelWrapper.VidHolder.rawChildren.addChild(loader);
	loader.content.addEventListener("onReady", onPlayerReady);
	loader.content.addEventListener("onError", onPlayerError);
	loader.content.addEventListener("onStateChange", onPlayerStateChange);
	loader.content.addEventListener("onPlaybackQualityChange", 
	onVideoPlaybackQualityChange);
}
			
private function onPlayerReady(event:Event):void {
	/** 
	 * 	Event.data contains the event parameter, 
	 * 	which is the Player API ID 
	 **/
	trace("player ready:", Object(event).data);
			
	/** 
	 *  Once this event has been dispatched by the player, we can use
	 *  cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl
	 *  to load a particular YouTube video.
	 **/
	player = loader.content;
	player.setSize(middlePanelWrapper.VidHolder.width, middlePanelWrapper.VidHolder.height);
}
			
private function onPlayerError(event:Event):void {
	/**
	 *  Event.data contains the event parameter, which is the error code
	 **/
	trace("player error:", Object(event).data);
}
			
private function onPlayerStateChange(event:Event):void {
	/**
	 *  Event.data contains the event parameter, which is the new player state
	 **/
	var newState:String = Object(event).data;
	if (newState.indexOf("1") == 0) {
		var title:String = middlePanelWrapper.searchResults.selectedItem.title;
		postTweet('Watching ' + title);
		getTweets();
	}
}
			
private function onVideoPlaybackQualityChange(event:Event):void {
	/** 
	 * Event.data contains the event parameter, which is the new video quality
	 **/
	trace("video quality:", Object(event).data);
}
         
private function doSearch(searchTerm:String):void {
	youtubeRemoteObject.youtubeRemote.searchVideo(searchTerm, 1, 10);
}
		           
private function searchListener(event:ResultEvent):void {
	var dp = new ArrayCollection(ArrayUtil.toArray(event.result));
	middlePanelWrapper.searchResults.dataProvider = dp;
}

private function playVideo(event:ListEvent):void {
    var videoId:String = event.currentTarget.selectedItem.videoId;   
	player.cueVideoById(videoId, 0, 'small');
}
		           	      
private function faultListener(event:FaultEvent):void {
	/**
 	 * Fault listener for RemoteObject
 	**/		
	Alert.show(event.fault.message, "Error");
}